package com.media.appmedia.util;

import java.util.Timer;
import java.util.TimerTask;

import android.os.Handler;
import android.os.Message;

/**
 * 倒计时类
 */
public class TimerDown {

	private Timer timer;
	private int timerNum;
	private Handler handler;

	/** 倒计时进行中 */
	public static final int DOWN_PROGRESS_MSG = 1;
	/** 倒计时结束 */
	public static final int DOWN_OVER_MSG = 2;

	public TimerDown(Handler handler) {
		this.handler = handler;
		initData();
	}

	private void initData() {
		timer = new Timer();
	}

	public void start() {
		timerNum = Const.MAX_GET_PHONE_NUMBER_TIMER;
		timer.schedule(task, 0, 1000);
	}

	public void cancel() {
		timer.cancel();
		task.cancel();
		handler.sendEmptyMessage(DOWN_OVER_MSG);
	}

	final TimerTask task = new TimerTask() {
		public void run() {
			Message msg = handler.obtainMessage();
			if (timerNum <= 1) {
				timer.cancel();
				msg.what = DOWN_OVER_MSG;
				handler.sendMessage(msg);
				// handler.sendEmptyMessage(DOWN_OVER_MSG);
			} else {
				--timerNum;
				msg.what = DOWN_PROGRESS_MSG;
				msg.arg1 = timerNum;
				handler.sendMessage(msg);

			}
		}
	};
	public void overTime(){
		timerNum = 0;
	}

}
